// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();

// 添加数据，用于获取口令或无口令抽奖
async function insertEnterIntoActivity(data, _openid) {
    let insert = null;
    if (data.command == undefined) {// 无口令抽奖
        insert = await db.collection('enter_into_activity').add({
            data: {
                _openid: _openid,
                activity_id: data.activity_id,
                activity_name: data.activity_name,
                command: data.command,
                _createTime: db.serverDate(),
                _updateTime: db.serverDate(),
                prize_gain: data.prize_gain,
                prize_name: data.prize_name,
                prize_logo: data.prize_logo,
            }
        })
    } else { // 获取口令
        insert = await db.collection('enter_into_activity').add({
            data: {
                activity_id: data.activity_id,
                activity_name: data.activity_name,
                command: data.command,
                _createTime: db.serverDate(),
                _updateTime: db.serverDate(),
            }
        })
    }
    return insert;
}
// 修改数据，用于口令抽奖
async function updateEnterIntoActivity(data, _openid) {
    data.setData._openid = _openid;
    let intoActivity = await db.collection('enter_into_activity').where(data.whereData).update({
        data: {
            _openid: _openid,
            _updateTime: db.serverDate(),
            prize_gain: data.setData.prize_gain,
            prize_name: data.setData.prize_name,
            prize_logo: data.setData.prize_logo,
        },
    });
    return intoActivity;
}
// 修改数据，用于获奖修改
async function updateActivityList(data) {
    let activityList = await db.collection('activity_list').where(data.whereData).update({
        data: {
            _updateTime: db.serverDate(),
            prizes: data.setData.prizes,
        },
    });
    return activityList;
}

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    console.log(wxContext.OPENID);
    switch(event.functionName) {// 判断用户使用什么方法
        case "insertEnterIntoActivity":
            let enterIntoActivity = await insertEnterIntoActivity(event.data, wxContext.OPENID);
            return {result: enterIntoActivity};
        case "updateEnterIntoActivity":
            let intoActivity = await updateEnterIntoActivity(event, wxContext.OPENID);
            return {result: intoActivity};
        case "updateActivityList":
            let activityList = await updateActivityList(event);
            return {result: activityList};
    }
    console.log("fail");
    return {
        result: {
            errMsg: 'no',
        }
    }

    // const wxContext = cloud.getWXContext()

    // return {
    //     event,
    //     openid: wxContext.OPENID,
    //     appid: wxContext.APPID,
    //     unionid: wxContext.UNIONID,
    // }
}